<template>
  <!--新增，编辑角色-->
  <dt-modal-edit ref="editRef" title="编辑角色" @ok="onOk">
    <Tabs type="card" :animated="false" v-model="showTab">
      <TabPane label="角色信息" name="roleMsg">
        <dt-info ref="msgRef"></dt-info>
      </TabPane>
      <TabPane label="功能权限" name="permission">
        <div style="max-height: 400px; overflow: auto">
          <Tree
            :data="permissionData"
            ref="treeRef"
            show-checkbox
            check-strictly
            check-directly
            @on-check-change="permissionChange"></Tree>
          <dt-loading ref="loadingRef" :loading="loading"></dt-loading>
        </div>
      </TabPane>
    </Tabs>
  </dt-modal-edit>
</template>

<script setup>
  import { watch, ref } from 'vue'
  import { editOpt } from '../biz/edit'
  import dt from '@dt/dt'
  import roleMgr from '../biz/index'

  const [editRef, msgRef, treeRef] = [ref(), ref(), ref()]
  const loading = ref(false)
  const editInfo = ref({})
  const permissionData = ref([])
  const permissionDataSouce = ref([]) // 编辑时，原有的权限
  const showTab = ref('roleMsg')
  const emits = defineEmits(['search'])
  watch(showTab, (newVal) => {
    if (newVal == 'permission') {
      getSaWebAuthList()
    }
  })

  function getSaWebAuthList() {
    // 权限树数据
    loading.value = true
    roleMgr.getSaAuthMenu({ roleTypeId: editInfo.value.roleTypeId }).then((res) => {
      loading.value = false
      permissionData.value = res
      resolveTree(permissionData.value, permissionDataSouce.value)
    })
  }

  function edit(row) {
    showTab.value = 'roleMsg'
    editInfo.value = { ...row }
    permissionDataSouce.value = dt.tool.deepClone(row.authIds || [])
    msgRef.value.init(new editOpt(), editInfo)
    editRef.value.show()
  }

  function onOk() {
    msgRef.value.validate().then((res) => {
      if (res) {
        let params = {
          id: editInfo.value.id,
          roleDesc: editInfo.value.roleDesc,
          authIds: editInfo.value.authIds
        }
        // 编辑
        roleMgr.roleUpdate(params).then((res) => {
          dt.ui.Message.success('修改成功')
          console.log(editInfo.value, '数据')
          emits('search')
          editRef.value.hide()
        })
      }
    })
  }

  function permissionChange(val, target) {
    editInfo.value.authIds = []
    dt.tool.treeChange(permissionData.value, target, treeRef.value).then((res) => {
      res.forEach((item) => {
        editInfo.value.authIds.push(item.id)
      })
    })
  }

  function resolveTree(treeData, ids) {
    treeData.forEach((item) => {
      if (ids.includes(Number(item.id))) {
        item.checked = true
      } else {
        item.checked = false
      }
      if (item.children && item.children.length > 0) {
        resolveTree(item.children, ids)
      }
    })
  }

  defineExpose({ edit })
</script>

<style scoped></style>
